
<template>
  <div class="chat-container">
    <div class="messages" ref="messagesContainer">
      <div v-for="(message, index) in messages" :key="index" :class="['message', message.role]">
        <div class="message-header">
          <div class="avatar" :class="message.role">
            <span v-if="message.role === 'user'">👤</span>
            <span v-else>🤖</span>
          </div>
          <div class="message-info">
            <span class="username">{{ message.role === 'user' ? 'You' : 'AI Assistant' }}</span>
            <span class="timestamp">{{ formatTime(message.timestamp) }}</span>
          </div>
        </div>
        <div class="message-body" v-html="formatContent(message.content)"></div>
      </div>
      <div v-if="isLoading" class="message assistant typing">
        <div class="message-header">
          <div class="avatar assistant">🤖</div>
          <div class="message-info">
            <span class="username">AI Assistant</span>
          </div>
        </div>
        <div class="message-body" v-html="formatContent(partialResponse)"></div>
        <div class="typing-indicator">
          <span class="dot"></span>
          <span class="dot"></span>
          <span class="dot"></span>
        </div>
      </div>
    </div>

    <div class="input-container">
      <div class="input-box">
        <textarea
            v-model="inputMessage"
            @keydown.enter.exact.prevent="sendMessage"
            @keydown.shift.enter.prevent="inputMessage += '\n'"
            placeholder="Type your message here..."
            rows="1"
            ref="textareaRef"
        ></textarea>
        <button
            class="send-button"
            @click="sendMessage"
            :disabled="isLoading || !inputMessage.trim()"
            :class="{ loading: isLoading }"
        >
          <svg v-if="!isLoading" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="20" height="20">
            <path fill="currentColor" d="M22 2L11 13M22 2L15 22L11 13M11 13L2 9" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
          </svg>
          <span v-else class="loading-dots">
            <span>.</span><span>.</span><span>.</span>
          </span>
        </button>
      </div>
      <div class="hint-text" v-if="messages.length === 0">
        Ask me anything... (Supports Markdown formatting)
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted, onBeforeUnmount } from 'vue';
import { marked } from 'marked';
import DOMPurify from 'dompurify';
import hljs from 'highlight.js';
import 'highlight.js/styles/github.css';
// 配置marked.js
marked.setOptions({
  highlight: (code, lang) => {
    const language = hljs.getLanguage(lang) ? lang : 'plaintext';
    return hljs.highlight(code, { language }).value;
  },
  langPrefix: 'hljs language-',
  breaks: true,
  gfm: true
});

const messages = ref([]);
const inputMessage = ref('');
const isLoading = ref(false);
const partialResponse = ref('');
const textareaRef = ref(null);
const messagesContainer = ref(null);
const controller = ref(null);

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
};

// 格式化内容（Markdown转HTML）
const formatContent = (content) => {
  if (!content) return '';

  // 转换Markdown
  let html = marked(content);

  // 净化HTML
  return DOMPurify.sanitize(html, {
    ALLOWED_TAGS: [
      'p', 'br', 'strong', 'em', 'code', 'pre', 'blockquote',
      'ul', 'ol', 'li', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
      'table', 'thead', 'tbody', 'tr', 'th', 'td', 'a', 'img',
      'div', 'span', 'hr'
    ],
    ALLOWED_ATTR: ['href', 'src', 'alt', 'title', 'target', 'class', 'style']
  });
};

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
    }
  });
};

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim() || isLoading.value) return;

  // 取消之前的请求（如果有）
  if (controller.value) {
    controller.value.abort();
  }

  const userMessage = {
    role: 'user',
    content: inputMessage.value,
    timestamp: new Date().getTime()
  };

  messages.value.push(userMessage);
  inputMessage.value = '';
  isLoading.value = true;
  partialResponse.value = '';

  await nextTick();
  scrollToBottom();

  const assistantMessage = {
    role: 'assistant',
    content: '',
    timestamp: new Date().getTime()
  };

  controller.value = new AbortController();

  try {
    const response = await fetch('http://localhost:8102/api/ai/chat', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        model: "qwen-turbo",
        input: {
          messages: messages.value.map(msg => ({
            role: msg.role,
            content: msg.content
          }))
        },
        parameters: {
          incrementalOutput: true,
          resultFormat: "message"
        }
      }),
      signal: controller.value.signal
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const reader = response.body.getReader();
    const decoder = new TextDecoder('utf-8');
    let buffer = '';

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      buffer += decoder.decode(value, { stream: true });

      const lines = buffer.split('\n\n');
      buffer = lines.pop() || '';

      for (const line of lines) {
        if (!line.trim()) continue;

        try {
          if (line.startsWith('data:')) {
            const jsonStr = line.substring(5).trim();
            if (jsonStr === '[DONE]') continue;

            const data = JSON.parse(jsonStr);
            if (data.output?.text) {
              assistantMessage.content = data.output.text;
              partialResponse.value = data.output.text;
              scrollToBottom();
            }
          }
        } catch (e) {
          console.error('Error parsing line:', e);
        }
      }
    }

    messages.value.push({ ...assistantMessage });
  } catch (error) {
    if (error.name !== 'AbortError') {
      console.error('Error:', error);
      messages.value.push({
        role: 'assistant',
        content: `⚠️ Error: ${error.message}`,
        timestamp: new Date().getTime()
      });
    }
  } finally {
    isLoading.value = false;
    controller.value = null;
    scrollToBottom();
  }
};

// 自动调整输入框高度
const adjustTextareaHeight = () => {
  if (textareaRef.value) {
    textareaRef.value.style.height = 'auto';
    textareaRef.value.style.height = `${Math.min(textareaRef.value.scrollHeight, 150)}px`;
  }
};

// 自动聚焦输入框
onMounted(() => {
  if (textareaRef.value) {
    textareaRef.value.focus();
    textareaRef.value.addEventListener('input', adjustTextareaHeight);
  }
});

// 清理
onBeforeUnmount(() => {
  if (textareaRef.value) {
    textareaRef.value.removeEventListener('input', adjustTextareaHeight);
  }
  if (controller.value) {
    controller.value.abort();
  }
});
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 100px);
  max-width: 1100px;
  margin: 0 auto;
  background-color: #f9f9f9;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 16px;
  background-color: #f5f5f7;
}

.message {
  display: flex;
  flex-direction: column;
  max-width: 85%;
  border-radius: 12px;
  padding: 12px 16px;
  animation: fadeIn 0.3s ease;
}

.message.user {
  align-self: flex-end;
  background-color: #007aff;
  color: white;
  border-bottom-right-radius: 4px;
}

.message.assistant {
  align-self: flex-start;
  background-color: white;
  border: 1px solid #e0e0e0;
  border-bottom-left-radius: 4px;
}

.message.typing {
  background-color: rgba(255, 255, 255, 0.8);
}

.message-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.avatar {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
  font-size: 14px;
  flex-shrink: 0;
}

.avatar.user {
  background-color: rgba(255, 255, 255, 0.2);
}

.avatar.assistant {
  background-color: #f0f0f0;
  color: #333;
}

.message-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.username {
  font-weight: 600;
  font-size: 14px;
}

.message.user .username {
  color: rgba(255, 255, 255, 0.9);
}

.timestamp {
  font-size: 11px;
  color: #999;
}

.message.user .timestamp {
  color: rgba(255, 255, 255, 0.7);
}

.message-body {
  line-height: 1.6;
  word-wrap: break-word;
  overflow-x: auto;
}

.message.user .message-body {
  color: white;
}

.message-body :deep(*) {
  margin-top: 0.5em;
  margin-bottom: 0.5em;
}

.message-body :deep(h1),
.message-body :deep(h2),
.message-body :deep(h3) {
  margin-top: 0.8em;
  margin-bottom: 0.5em;
}

.message-body :deep(code) {
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
  font-size: 0.9em;
  padding: 0.2em 0.4em;
  border-radius: 3px;
}

.message.user .message-body :deep(code) {
  background-color: rgba(255, 255, 255, 0.2);
  color: inherit;
}

.message.assistant .message-body :deep(code) {
  background-color: #f0f0f0;
  color: #333;
}

.message-body :deep(pre) {
  background-color: #f8f8f8;
  border-radius: 6px;
  padding: 12px;
  overflow-x: auto;
  margin: 8px 0;
}

.message.user .message-body :deep(pre) {
  background-color: rgba(0, 0, 0, 0.2);
  color: white;
}

.message-body :deep(blockquote) {
  border-left: 4px solid #ddd;
  padding-left: 12px;
  color: #666;
  margin-left: 0;
}

.message-body :deep(table) {
  border-collapse: collapse;
  width: 100%;
  margin: 8px 0;
}

.message-body :deep(th),
.message-body :deep(td) {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

.message-body :deep(ul),
.message-body :deep(ol) {
  padding-left: 20px;
  margin: 8px 0;
}

.input-container {
  padding: 16px;
  background-color: white;
  border-top: 1px solid #e0e0e0;
}

.input-box {
  display: flex;
  align-items: flex-end;
  gap: 10px;
}

textarea {
  flex: 1;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 12px 16px;
  font-family: inherit;
  font-size: 15px;
  line-height: 1.5;
  resize: none;
  outline: none;
  transition: border-color 0.2s;
  max-height: 150px;
  min-height: 50px;
}

textarea:focus {
  border-color: #007aff;
}

.send-button {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  background-color: #007aff;
  color: white;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
  flex-shrink: 0;
}

.send-button:hover {
  background-color: #0062cc;
}

.send-button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.send-button.loading {
  background-color: #999;
}

.loading-dots span {
  animation: blink 1.4s infinite both;
  font-size: 20px;
  line-height: 0;
}

.loading-dots span:nth-child(2) {
  animation-delay: 0.2s;
}

.loading-dots span:nth-child(3) {
  animation-delay: 0.4s;
}

.typing-indicator {
  display: flex;
  gap: 6px;
  margin-top: 8px;
}

.dot {
  width: 8px;
  height: 8px;
  background-color: #999;
  border-radius: 50%;
  display: inline-block;
  animation: bounce 1.4s infinite ease-in-out both;
}

.dot:nth-child(1) {
  animation-delay: -0.32s;
}

.dot:nth-child(2) {
  animation-delay: -0.16s;
}

.hint-text {
  text-align: center;
  font-size: 13px;
  color: #999;
  margin-top: 8px;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

@keyframes bounce {
  0%, 80%, 100% { transform: scale(0); }
  40% { transform: scale(1); }
}

@keyframes blink {
  0%, 100% { opacity: 0.2; }
  50% { opacity: 1; }
}
</style>
